package org.csu.springjpetstore.web.filter;

import org.csu.springjpetstore.domain.Account;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebFilter(filterName = "LogFilter")
public class LogFilter implements Filter {
    private PrintWriter writer;
    private String prefix;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        prefix = filterConfig.getInitParameter("LogFilter");
        try {
            // 采用FileWriter 避免每次调用PrintWriter时将txt文件全部清空。
            FileWriter fileWriter = new FileWriter("log.txt", true);

            writer = new PrintWriter(fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String IP = request.getRemoteAddr();
        String requestURI = request.getRequestURI();
        HttpSession session = request.getSession();
        if (IP.equals("")) {
            System.out.println("###");
        }

        Account loginuser = (Account) session.getAttribute("loginuser");
        String username = (String) session.getAttribute("username");
        if (username == null)
            writer.println(IP + "localhost" + "          " + new Date() + "           " + prefix + "         " + requestURI);
        else
            writer.println(IP + username + "          " + new Date() + "           " + prefix + "         " + requestURI);
        writer.flush();
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("摧毁过滤器");
        if (writer != null)
            writer.close();
    }
}
